package model;
import xl.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Observable;

public class Sheet extends Observable implements Environment{
	private HashMap<Address,Cell> sheet;
	private CellFactory factory;
	private String name;
	
	

	public Sheet(String name){
		this.name = name;
		sheet = new HashMap<Address,Cell>();
		factory = new CellFactory();
	}
	
	public void put(Address address, String input) {
		Cell cell = null;
		try {
			cell = factory.createCell(input);
		} catch (XLException e) {			
			setChanged();			
			notifyObservers(e);
			return;
		}
		sheet.put(address, new NullCell());
		try {
			cell.getValue(this);
			sheet.put(address, cell);
			setChanged();			
			notifyObservers("");
		} catch (XLException e) {
			sheet.remove(address);
			setChanged();			
			notifyObservers(e);
		}
	}
	
	public HashMap<Address,Cell> getSheet(){
		return sheet;		
	}

	
	public void clear(Address address){
		sheet.remove(address);
		setChanged();
		notifyObservers("");
	}
	
	public void clearAll(){
		sheet = new HashMap<Address,Cell>();
		setChanged();
		notifyObservers("");
	}

	
	public double value(Object key) {    	
    	Address keyTemp = (Address)key;
    	Cell cell = sheet.get(keyTemp);
    	if(cell == null){
    		return  0;
    	}else{
    		return cell.getValue(this);
    	}
    	
    	}
	
	public void update(){
		setChanged();
		notifyObservers("");
	}
}
